<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="计划名称" prop="taskName">
                <el-input style="width: 11vw" v-model="queryParams.taskName" placeholder="请输入计划名称" clearable/>
            </el-form-item>
            <el-form-item label="巡检班组" prop="inspectionTeams">
                <el-select v-model="queryParams.inspectionTeams" placeholder="请选择巡检班组" clearable>
                    <el-option v-for="team in teamName" :value="team.teamId" :label="team.teamName"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['ar_check:plan:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['ar_check:plan:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['ar_check:plan:remove']"
                >删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" plain icon="Upload" @click="handleTeamImport"
                           v-hasPermi="['system:plan:import']">
                    导入
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['ar_check:plan:export']"
                >导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" :selectable="selectionEnable"/>
            <el-table-column label="任务名称" align="center" prop="taskName">
                <template #default="{row}">
                    <el-button type="primary" link @click="detailedInformation(row)">{{ row.taskName }}</el-button>
                </template>
            </el-table-column>

            <el-table-column label="巡检类型" align="center" prop="frequencyType">
                <template #default="{row}">
                    <dict-tag :options="inspection_type" :value="row.frequencyType"/>
                </template>
            </el-table-column>
            <!--            <el-table-column label="巡检区域" align="center" prop="inspectionAreas"/>-->
            <el-table-column label="巡检班组" align="center" prop="teamName"/>
            <!--            <el-table-column label="巡检项目" align="center" prop="inspectionItems"/>-->
            <el-table-column label="创建人" align="center" prop="createBy"/>
            <el-table-column label="创建时间" align="center" prop="createTime" width="160"/>
            <el-table-column label="开始日期" align="center" prop="startDate" width="160"/>
            <el-table-column label="结束日期" align="center" prop="endDate" width="160"/>
            <el-table-column label="更新人" align="center" prop="updateBy"/>
            <el-table-column label="更新时间" align="center" prop="updateTime" width="160"/>
            <el-table-column label="审核人" align="center" prop="reviewer"/>
            <el-table-column label="状态" align="center" prop="status">
                <template #default="{row}">
                    <span v-if="row.status === 'Unaudited'">未申请</span>
                    <el-tag v-else :type="getStatus(row, true)">{{ getStatus(row, false) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="notes"/>
            <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width">
                <template #default="{row}">
                    <el-button link type="primary"
                               :disabled="!(row.status === 'Unaudited' || row.status === 'rejection')"
                               @click="apply(row)" v-hasPermi="['ar_check:plan:edit']">
                        <template #icon>
                            <svg-icon icon-class="plan_apply"/>
                        </template>
                        {{ row.status === 'rejection' ? '重新申请' : '申请' }}
                    </el-button>
                    <el-button link type="primary"
                               :disabled="!(row.status === 'Unaudited' || row.status === 'rejection')
                               && row.status !== 'Completed'" icon="Edit"
                               @click="handleUpdate(row)" v-hasPermi="['ar_check:plan:edit']">修改
                    </el-button>
                    <el-button link type="primary"
                               :disabled="!(row.status === 'Unaudited' || row.status === 'rejection')" icon="Delete"
                               @click="handleDelete(row)"
                               v-hasPermi="['ar_check:plan:remove']">删除
                    </el-button>
                    <el-button link type="primary" icon="List" @click="showDefect(row)"
                               v-hasPermi="['ar_check:team:query']">
                        查看巡检情况
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="getList"
        />

        <!-- 添加或修改巡检计划对话框 -->
        <el-dialog :title="title" v-model="open" width="680px" append-to-body>
            <el-form ref="planRef" inline :model="form" :rules="rules" label-width="80px">
                <el-form-item label="任务名称" prop="taskName">
                    <el-input v-model="form.taskName" placeholder="请输入任务名称"/>
                </el-form-item>
                <el-form-item label="巡检类型" prop="frequencyType">
                    <el-select style="width: 11.6vw" v-model="form.frequencyType" clearable
                               placeholder="请选择巡检类型">
                        <el-option v-for="item in inspection_type" :key="item.value" :label="item.label"
                                   :value="item.value"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="巡检次数" prop="frequencyValue">
                    <el-input v-model="form.frequencyValue" type="number" placeholder="请输入巡检次数"/>
                </el-form-item>
                <el-form-item label="巡检区域" prop="areas">
                    <el-select style="width: 11.6vw" collapse-tags multiple v-model="form.areas" clearable
                               placeholder="请选择巡检区域">
                        <el-option v-for="item in centerList" :key="item.roomName" :label="item.roomName"
                                   :value="item.roomId"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="开始日期" prop="startDate">
                    <el-date-picker clearable v-model="form.startDate" type="datetime" style="width: 10.3vw;"
                                    value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束日期" prop="endDate">
                    <el-date-picker clearable
                                    v-model="form.endDate"
                                    type="datetime"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    placeholder="请选择结束日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="巡检班组" prop="inspectionTeams">
                    <el-select style="width: 10.3vw" v-model="form.inspectionTeams" clearable
                               placeholder="请选择巡检班组">
                        <el-option v-for="item in teamName" :key="item.teamName" :label="item.teamName"
                                   :value="item.teamId" :disabled="item.disable"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="notes">
                    <el-input v-model="form.notes" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
                <el-divider content-position="center">巡检项目信息</el-divider>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" icon="Plus" @click="handleAddInspectionProject">添加</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" icon="Delete" @click="handleDeleteInspectionProject">删除</el-button>
                    </el-col>
                </el-row>
                <el-table class="list" :data="inspectionProjectList" :row-class-name="rowInspectionProjectIndex"
                          @selection-change="handleInspectionProjectSelectionChange" ref="inspectionProject">
                    <el-table-column type="selection" width="50" align="center"/>
                    <el-table-column label="序号" align="center" prop="index" width="50"/>
                    <el-table-column label="项目名称" prop="projectName" width="150">
                        <template #default="{row}">
                            <el-select v-model="row.projectName" @change="checkClick(row)" clearable
                                       placeholder="请选择项目名称">
                                <el-option v-for="item in projectList" :key="item.projectId" :value="item.projectId"
                                           :disabled="item.disable" :label="item.projectName"/>
                            </el-select>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!--    excel导入    -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <el-upload :action="upload.url" ref="uploadRef" :limit="1" accept=".xlsx"
                       :on-progress="handleFileProgress"
                       :disabled="upload.isUploading" :auto-upload="false" drag
                       :headers="upload.headers" :on-success="handleFileSuccess">

                <el-icon class="el-icon--upload">
                    <UploadFilled/>
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

                <template #tip>
                    <div class="el-upload__tip text-center">
                        <span>仅允许导入xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                                 @click="importTemplate">
                            下载模板
                        </el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <info ref="info"/>
        <defect-list ref="defectTab"/>

    </div>
</template>

<script setup>
import { listPlan, getPlan, delPlan, addPlan, updatePlan, planApply } from '@/api/ar_check/plan'
import { getTeamListAll } from '@/api/ar_check/team.js'
import { listCenterAll } from '@/api/ar_check/center.js'
import { listProjectAll } from '@/api/ar_check/project.js'
import DictTag from '@/components/DictTag/index.vue'
import SvgIcon from '@/components/SvgIcon/index.vue'
import Info from '@/views/ar_check/plan/info.vue'
import { dayjs } from 'element-plus'
import { getPlanByIdDefect } from '@/api/ar_check/defects.js'
import DefectList from '@/views/ar_check/defects/components/defectList.vue'
import { getToken } from '@/utils/auth.js'
import { UploadFilled } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()

defineOptions({
    name: 'Plan'
})

const planList = ref([])
const inspectionProjectList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedInspectionProject = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const teamName = ref([])
const centerList = ref([])
const projectList = ref([])
const { inspection_type, inspection_status } = proxy.useDict('inspection_type', 'inspection_status')
const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        frequencyType: null,
        frequencyValue: null,
        areas: null,
        auditTime: null,
        startDate: null,
        endDate: null,
        inspectionTeams: null,
        inspectionItems: null,
        status: null,
        notes: null
    },
    rules: {
        taskName: [
            { required: true, message: '任务名称不能为空', trigger: 'blur' }
        ],
        frequencyType: [
            { required: true, message: '巡检类型', trigger: 'blur' }
        ],
        frequencyValue: [
            { required: true, message: '巡检次数不能为空', trigger: 'blur' }
        ],
        areas: [
            { required: true, message: '巡检区域不能为空', trigger: 'blur' }
        ],
        auditTime: [
            { required: true, message: '审核时间不能为空', trigger: 'blur' }
        ],
        startDate: [
            { required: true, message: '开始日期不能为空', trigger: 'blur' }
        ],
        endDate: [
            { required: true, message: '结束日期不能为空', trigger: 'blur' },
            { validator: validateEndDate, trigger: 'blur' }
        ],
        inspectionTeams: [
            { required: true, message: '巡检班组不能为空', trigger: 'blur' }
        ],
        inspectionItems: [
            { required: true, message: '巡检项目不能为空', trigger: 'blur' }
        ],
        status: [
            {
                required: true,
                message: '状态',
                trigger: 'blur'
            }
        ],
    }
})

/** 校验时间*/
function validateEndDate(rule, value, callback) {
    // 判断开始日期是否为空
    if (!form.value.startDate) {
        // 如果开始日期为空，不进行结束日期的校验
        callback(new Error('开始日期不能为空！'))
    }
    // 将日期字符串转换为 Date 对象
    const startDate = new Date(form.value.startDate)
    const endDate = new Date(value)
    // 检查结束日期是否早于开始日期
    if (endDate < startDate) {
        callback(new Error('结束日期不能早于开始日期'))
    } else {
        callback()
    }
}

const { queryParams, form, rules } = toRefs(data)

/*** 用户导入参数 */
const upload = ref({
    open: false,
    title: '计划导入',
    // 是否禁用上传
    isUploading: false,
    headers: { Authorization: 'Bearer ' + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + '/ar_check/plan/importData'
})

/** 查询巡检计划列表 */
function getList() {
    loading.value = true
    listPlan(queryParams.value).then(response => {
        planList.value = response.rows
        total.value = response.total
        loading.value = false
    })
}

// 取消按钮
function cancel() {
    open.value = false
    reset()
}

// 表单重置
function reset() {
    form.value = {
        planId: null,
        taskName: null,
        frequencyType: null,
        frequencyValue: null,
        reviewer: null,
        areas: null,
        auditTime: null,
        startDate: null,
        endDate: null,
        inspectionTeams: null,
        inspectionItems: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        status: null,
        notes: null
    }
    inspectionProjectList.value = []
    proxy.resetForm('planRef')
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm('queryRef')
    handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.planId)
    single.value = selection.length !== 1
    multiple.value = !selection.length
}

/*查询未分配的班组列表*/
async function getTeamName() {
    const { data } = await getTeamListAll()
    teamName.value = data
}

/*查询机房列表*/
async function getCenterList() {
    const { data } = await listCenterAll()
    centerList.value = data
}

/** 新增按钮操作 */
function handleAdd() {
    reset()
    getProjectList()
    open.value = true
    title.value = '添加巡检计划'
    getTeamName()//获取班组列表
    getCenterList()//获取机房列表
}

/** 修改按钮操作 */
async function handleUpdate(row) {
    reset()
    const _planId = row.planId || ids.value
    const { data } = await getPlan(_planId)
    await getCenterList() //获取机房列表
    await getTeamName() //获取班组列表
    await getProjectList()
    form.value = data
    form.value.areas = data.inspectionAreas.split(',').map(Number)
    const projectIdArrays = data.inspectionItems.split(',')
    inspectionProjectList.value = projectIdArrays.map((s, index) => ({
        id: +s,
        index: index + 1,
        projectName: +s
    }))
    projectList.value.forEach(value => {
        if (projectIdArrays.includes(value.projectId.toString())) {
            disableCheck(value.projectId, true)
        }
    })
    open.value = true
    title.value = '修改巡检计划'
}

/** 提交按钮 */
async function submitForm() {
    const valid = await proxy.$refs['planRef'].validate()
    if (valid) {
        form.value.inspectionProjectList = inspectionProjectList.value
        if (form.value.planId != null) {
            form.value.inspectionItems = inspectionProjectList.value.map(item => item.projectName).toString()
            form.value.inspectionAreas = form.value.areas.toString()
            await updatePlan(form.value)
            proxy.$modal.msgSuccess('修改成功')
            open.value = false
            getList()
        } else {
            form.value.inspectionItems = inspectionProjectList.value.map(item => item.projectName).toString()
            form.value.inspectionAreas = form.value.areas.toString()
            await addPlan(form.value)
            proxy.$modal.msgSuccess('新增成功')
            open.value = false
            getList()
        }
    }
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _planIds = row.planId || ids.value
    proxy.$modal.confirm('是否确认删除巡检计划编号为"' + _planIds + '"的数据项？').then(function () {
        return delPlan(_planIds)
    }).then(() => {
        getList()
        proxy.$modal.msgSuccess('删除成功')
    }).catch(() => {
    })
}

/** 巡检项目序号 */
function rowInspectionProjectIndex({ row, rowIndex }) {
    row.index = rowIndex + 1
}

/** 巡检项目添加按钮操作 */
function handleAddInspectionProject() {
    let obj = {}
    obj.projectName = null
    obj.id = null
    inspectionProjectList.value.push(obj)
}

/** 巡检项目删除按钮操作 */
function handleDeleteInspectionProject() {
    if (checkedInspectionProject.value.length === 0) {
        proxy.$modal.msgError('请先选择要删除的巡检项目数据')
    } else {
        const checkedInspectionProjects = checkedInspectionProject.value
        checkedInspectionProjects.forEach(value => {
            const data = inspectionProjectList.value.find(val => val.index === value)
            disableCheck(data.projectId, false)
            data.id = ''
        })
        inspectionProjectList.value = inspectionProjectList.value.filter(function (item) {
            return checkedInspectionProjects.indexOf(item.index) === -1
        })
    }
}

/** 复选框选中数据 */
function handleInspectionProjectSelectionChange(selection) {
    checkedInspectionProject.value = selection.map(item => item.index)
}

/*选中成员*/
function checkClick(row) {
    if (row.projectName) {
        if (row.id)
            disableCheck(row.id, false)
        row.id = row.projectName
        disableCheck(row.projectName, true)
    } else {
        disableCheck(row.id, false)
        row.id = ''
    }
}

/*禁用开关*/
function disableCheck(id, flag) {
    if (!id) return
    const member = projectList.value.find(value => value.projectId === id)
    member.disable = flag
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('ar_check/plan/export', {
        ...queryParams.value
    }, `plan_${new Date().getTime()}.xlsx`)
}

/** 获取项目列表*/
async function getProjectList() {
    const { data } = await listProjectAll()
    projectList.value = data
}

/** 打开详细列表 */
function detailedInformation(row) {
    proxy.$refs.info.open(row)
}

/*发起申请*/
async function apply(row) {
    const { planId, status } = row
    const extractedObject = { planId, status }
    await proxy.$modal.confirm(`确认要申请名称为：${row.taskName}的任务吗？`)
    const { data } = await planApply(extractedObject)
    if (data) {
        proxy.$modal.msgSuccess('申请成功')
        getList()
    }
}

/** 是否可选*/
function selectionEnable(row) {
    return (row.status === 'Unaudited' || row.status === 'rejection')
}

function getStatus(row, flag) {
    if (Object.keys(row).length === 0) return
    const start = dayjs(row.startDate)
    const end = dayjs(row.endDate)
    const current = dayjs()
    // 判断当前时间是否在指定范围内
    const between = current.isAfter(start) && current.isBefore(end)
    if (between) {
        if (row.status !== 'Approved') {
            const status = inspection_status.value.find(value => value.value === row.status)
            return flag ? status.value === 'Pending' ? 'warning' : status.value === 'Completed' ? 'success' : status.value === 'rejection' ? 'warning' : 'primary'
                : status.value === 'Pending' ? '待审核' : status.value === 'Completed' ? '已完成' : status.value === 'rejection' ? '已驳回' : '未知'
        }
        return flag ? 'primary' : '进行中'
    } else {
        // 比较两个时间对象
        return flag ? current.isBefore(end) ? 'info' : 'danger' : current.isBefore(end) ? '未开始' : '已结束'
    }
}

// 查看缺陷设备
async function showDefect({ planId, taskName }) {
    const { data } = await getPlanByIdDefect(planId)
    proxy.$refs.defectTab.open(data, taskName)
}

// 打开导入
function handleTeamImport() {
    upload.value.open = true
}

// 文件上传中
function handleFileProgress() {
    upload.value.isUploading = true
}

// 文件上传完成
function handleFileSuccess(response, file) {
    upload.value.open = false
    upload.value.isUploading = false
    proxy.$refs['uploadRef'].handleRemove(file)
    proxy.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' +
        response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
    getList()
}

// 下载模板
function importTemplate() {
    proxy.download('ar_check/plan/importTemplate', {}, `plan_template_${new Date().getTime()}.xlsx`)
}

// 确定上传
async function submitFileForm() {
    proxy.$refs.uploadRef.submit()
}

getList()
</script>
<style>
.app-container .el-table__body, .el-table__footer, .el-table__header {
    width: 100% !important;
}

.list .el-table__body, .el-table__footer, .el-table__header {
    width: 100% !important;
}
</style>
